/*
 * UpStoneCombineResource.cpp
 *
 *  Created on: 2014. 3. 6.
 *      Author: mega
 */

#include <algorithm>
#include <Toolkit/Str.h>
#include <Database/Static.h>
#include "UpStoneCombineResource.h"

#include "../macro.h"

namespace ProjectZ { namespace NResource {

UpStoneCombineResource::UpStoneCombineResource()
{

}

UpStoneCombineResource::~UpStoneCombineResource()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](UPSTONECOMBINETREE::value_type & pair) {
		delete pair.second;
	});
}

void
UpStoneCombineResource::Clear()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](UPSTONECOMBINETREE::value_type & pair) {
		delete pair.second;
	});
	clsFlyTree.clear();
}

bool
UpStoneCombineResource::LoadResource()
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT * FROM resource_upstone_combine");

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		Toolkit::Str<30> DESC;
		Flyweight * pFly = new Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> pFly->_QUALITY >> pFly->_RATE >> DESC;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsFlyTree[pFly->_QUALITY] = pFly;
	}

	return true;
}

UpStoneCombineResource::Flyweight *
UpStoneCombineResource::GetFly(int quality)
{
	auto iter = clsFlyTree.find(quality);
	if (iter == clsFlyTree.end())
		return NULL;

	return iter->second;
}

} /*NResource*/ } /*ProjectZ*/
